<template>
  <div id="app">
    <el-upload
      ref="upload"
      multiple
      action="http://upload.qiniup.com"
      :data="TokenQiNiu"
      :before-upload="beforeUpload"
      :http-request="uploadFile"
      :on-success="handleUploadSuccess"
      list-type="picture"
      :file-list="fileUploadList">
      <el-button type="primary" icon="el-icon-plus">选择图片</el-button>
    </el-upload>

    <!-- :before-upload= 上传文件之前的钩子(file) -->
    <!-- :before-remove= 删除文件之前的钩子(file,fileList) -->
    <!-- :http-request= 覆盖默认的上传行为(el-upload)-->
    <!-- :on-success= 文件上传成功时的钩子(response, file, fileList)-->
    <!--  -->
    <router-view />
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js';

export default {
  name: 'App',
  components: {},
  data() {
    return {
      pe: process.env,
      isDev: process.env.NODE_ENV === 'development',
      qiniu: {
        token: '',
        address: 'http://qiniuoss.chenxi618.com',
      },
      fileUploadList: [],
    };
  },
  computed: {
    TokenQiNiu: function () {
      return {
        token: this.qiniu.token,
      };
    },
  },
  methods: {
    /* 上传图片相关 s */
    clearFiles() {
      this.$refs.upload.clearFiles();
      this.fileUploadList.splice(0, this.fileUploadList.length);
    },
    beforeUpload(file) {
      if (file.type != 'image/png' && file.type != 'image/jpeg') {
        this.$message({
          message: '请上传正确的图片',
          type: 'warning',
        });
        return false;
      }
    }, // 上传之前回调
    uploadFile(elUpload) {
      return this.$api.getQiniuToken().then((res) => {
        console.log(elUpload);
        let token = res.data;
        let match = elUpload.file.name.match(/([^\/]+)\.(\w+)$/);
        let newFileName = `${this.$mock.mock('@uuid')}${match[1]}.${match[2]}`;

        let config = {
          useCdnDomain: true, //是否使用七牛的CDN加速域名上传，默认为false，上传后获取的文件地址为七牛存储空间的原始URL。
          region: qiniu.region.z0, //指定文件上传的区域，例如z0:华东,z1:华北,z2:华南,na0:北美。
        };
        let putExtra = {
          fname: newFileName, //用于指定上传的文件名，如果不指定，则默认使用上传文件的原始文件名。
          params: {}, //用于指定上传文件的扩展参数，例如文件类型、文件大小、上传时间等。
        };
        let key = newFileName;
        let observable = qiniu.upload(
          elUpload.file,
          key,
          token,
          putExtra,
          config
        );
        return new Promise((resolve, reject) => {
          observable.subscribe({
            next(res) {
              console.log(res);
            },
            error(err) {
              reject(err);
            },
            complete(res) {
              resolve(res);
            },
          });
        });
      });
    },
    handleProgress(event, file, fileList) {},
    handleUploadSuccess(response, file, fileList) {
      console.log(
        '%c [ response ]-105',
        'font-size:13px; background:pink; color:#bf2c9f;',
        response
      );
      // 如果只使用控件原生上传只会返回{hash:hash,key:hash}
      // 必须使用qiniu创建 监听对象 observable，通过key或putExtra.fname配置新文件名才能获得{hash:hash,key:key/putExtra.fname}
      this.fileUploadList.splice(0, this.fileUploadList.length);
      fileList.forEach((v, i, a) => {
        v.url = `${this.qiniu.address}/${v.response.key}`;
        this.fileUploadList.push(v);
      });
    }, // 上传成功
    uploadError() {
      this.$message.error(`图片上传失败`);
      return;
    },
    handleRemove(file, fileList) {},

    /* e 上传图片相关 */
    uploadFun() {
      return {
        handlePreview(file) {}, // :on-preview;点击文件列表中已上传的文件时的钩子
        handleRemove(file, fileList) {}, // :on-remove;文件列表移除文件时的钩子
        handleSuccess(response, file, fileList) {}, // :on-success;文件上传成功时的钩子
        handleError(err, file, fileList) {}, // :on-error;文件上传失败时的钩子
        handleProgress(event, file, fileList) {}, // :on-progress;文件上传时的钩子
        handleChange(file, fileList) {}, // :on-change	文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        handleBeforeUpload(file) {}, // :before-upload;上传文件之前的钩子，
        handleBeforeRemove(file, fileList) {}, // :before-remove;删除文件之前的钩子,
        handleUpload(elupload) {}, //:http-request;覆盖默认的上传行为，
        handleExceed(files, fileList) {}, // :on-exceed;文件超出个数限制时的钩子
      };
    },
  },
  beforeCreate: function () {}, // 实例初始化之后，数据观测和事件绑定之前
  created: function () {}, // 实例初始化完成，挂载尚未开始时
  beforeMount: function () {}, // 挂载之前，rander函数首次被调用时，常用于加载身份数据和一些后台可配置的选项
  mounted: function () {}, //在实例挂载到DOM节点上之后
  beforeUpdate: function () {}, // 数据更新时，在虚拟DOM状态变化之前
  updated: function () {}, // 虚拟DOM被重新渲染之后
  beforeDestroy: function () {}, // 实例销毁之前，此时实例依然可用
  destroyed: function () {}, // 实例销毁后，此时实例及其子实例将完全解绑
};
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100%;
}
</style>
